home *** CD-ROM | disk | FTP | other *** search
- Path: news.magi.com!news!news.magi.com
- From: nredding@magi.com (Neil Redding)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Fri, 19 Jan 1996 23:28:30 -0500
- Organization: Magi Data Consulting
- Message-ID: <nredding-1901962328300001@magi05p71.magi.com>
- References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com> <nredding-1901962245370001@magi04p72.magi.com>
- NNTP-Posting-Host: magi05p71.magi.com
-
- In article <nredding-1901962245370001@magi04p72.magi.com>,
- nredding@magi.com (Neil Redding) wrote:
-
-
- >If n is a power of 2, repeatedly multiplying n by 2 will eventually give you
- >2**32 == 0 when it overflows. Also shifting left one bit ( n<<1) is the same
- >as multiplying by 2.
- >Thus:
- >
- >
- >Boolean IsPowerOfTwo( unsigned long n )
- >{
- > short k = 31;
- > if ( n == 0 )
- > return false;
- > while ( k-- > 0 )
- > if ( (n <<= 1 ) == 0 )
- > return true;
- > return false;
- >}
- >
- >--
- Sorry...I realized just after sending this that it is also incorrect.
- Robert Fry's solution
- looks good though.
-
- --
- Neil Redding
- Ottawa, Canada
-